#pragma once
#ifndef _DBSERVICE_HPP_
#define _DBSERVICE_HPP_
#include <pthread.h>
#include <cppconn/connection.h>
#include "EventLoop.h"
#include <vector>
#include <cstdlib>
#include <cfloat>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/resultset_metadata.h>
#include <cppconn/statement.h>
#include "Mylogger.h"
#include "DbConnectionPool.h"
#include "cppconn//prepared_statement.h"
namespace SOS{

class Dbservice
{
public:
    Dbservice(DbConnectionPool &pool):_pool(pool) {}
    ~Dbservice() {}
    std::vector<std::vector<std::string>> sqlRead(const std::string &sql){
      auto* conn = _pool.getConnection(); // 获取连接
      std::vector<std::vector<std::string>> results;
    
      try {
        sql::Statement* stmt = conn->createStatement();
        sql::ResultSet* res = stmt->executeQuery(sql);
        if(!res){
            LOGDEBUG("SQL SELECT NO\n");
            return {};
        }
        // 获取元数据
        sql::ResultSetMetaData* meta = res->getMetaData();
        int columnCount = meta->getColumnCount();
        
        // 添加列名
        std::vector<std::string> columns;
        for (int i = 1; i <= columnCount; ++i) {
            columns.push_back(meta->getColumnLabel(i));
        }
        results.push_back(columns);
        
        // 遍历结果集
        while (res->next()) {
            std::vector<std::string> row;
            for (int i = 1; i <= columnCount; ++i) {
                row.push_back(res->getString(i));
            }
            results.push_back(row);
        }
        
        // 清理资源
        delete res;
        delete stmt;
        _pool.releaseConnection(conn);
        return results;
    } catch (...) {
      _pool.releaseConnection(conn); // 异常时归还连接
      LOGDEBUG("SQLException\n");
      throw;
    }
}

    
    bool sqlWrite(const std::string &sql){
        auto* conn = _pool.getConnection(); // 从连接池获取连接
        try {
            sql::Statement* stmt = conn->createStatement();
            int updateCount = stmt->executeUpdate(sql);
            printf("affected:%d\n",updateCount);
            delete stmt; // 必须手动删除
            _pool.releaseConnection(conn); // 归还连接
            return updateCount > 0;
        } catch (sql::SQLException& e) {
            _pool.releaseConnection(conn); // 异常时仍需归还
            LOGDEBUG("SQL ERROR",e.getErrorCode(),":",e.what(),"\n");
            return false;
        }
}


private:
    DbConnectionPool &_pool;
};

} // end of namespace SOS;

#endif

